package com.htthorizon.model.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONException;
import com.alibaba.fastjson2.JSONObject;
import com.htthorizon.common.core.utils.StringUtils;
import com.htthorizon.model.request.ModelSourceParamReq;
import com.htthorizon.model.request.ModelSourceReq;
import com.htthorizon.model.response.RemoteDataInfoDto;
import com.htthorizon.model.service.IModelSourceParamService;
import com.htthorizon.util.HttpRequestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import com.htthorizon.common.log.annotation.Log;
import com.htthorizon.common.log.enums.BusinessType;
import com.htthorizon.common.security.annotation.RequiresPermissions;
import com.htthorizon.model.domain.ModelSource;
import com.htthorizon.model.service.IModelSourceService;
import com.htthorizon.common.core.web.controller.BaseController;
import com.htthorizon.common.core.web.domain.AjaxResult;
import com.htthorizon.common.core.utils.poi.ExcelUtil;
import com.htthorizon.common.core.web.page.TableDataInfo;

/**
 * 数据源配置Controller
 *
 * @author mark
 * @date 2023-11-20
 */
@RestController
@RequestMapping("/model/source")
public class ModelSourceController extends BaseController
{
    @Autowired
    private IModelSourceService modelSourceService;

    @Autowired
    private IModelSourceParamService modelSourceParamService;

    /**
     * 查询数据源配置列表
     */
    @GetMapping("/list")
    @RequiresPermissions("model:source:list")
    @Log(title = "模型管理/模型数据源", businessType = BusinessType.QUERY)
    public TableDataInfo list(ModelSource modelSource)
    {
        startPage();
        List<ModelSource> list = modelSourceService.selectModelSourceList(modelSource);
        return getDataTable(list);
    }
    @GetMapping("/innerList")
    public TableDataInfo list2(ModelSource modelSource, @RequestParam(value = "pageNum", required = false)Integer pageNum ,@RequestParam(value = "pageSize", required = false)Integer pageSize)
    {
        startPage();
        List<ModelSource> list = modelSourceService.selectModelSourceList2(modelSource,pageNum,pageSize);
        return getDataTable(list);
    }
    @GetMapping(value = "getId/{id}")
    public AjaxResult getInfo2(@PathVariable("id") Long id)
    {
        return success(modelSourceService.selectModelSourceById(id));
    }

    /**
     * 导出数据源配置列表
     */
    @RequiresPermissions("model:source:export")
    @Log(title = "模型管理/数据源配置", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ModelSource modelSource)
    {
        List<ModelSource> list = modelSourceService.selectModelSourceList(modelSource);
        ExcelUtil<ModelSource> util = new ExcelUtil<ModelSource>(ModelSource.class);
        util.exportExcel(response, list, "数据源配置数据");
    }

    /**
     * 获取数据源配置详细信息
     */
    @RequiresPermissions("model:source:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(modelSourceService.selectModelSourceById(id));
    }

    /**
     * 新增数据源配置
     */
    @RequiresPermissions("model:source:add")
    @Log(title = "模型管理/数据源配置", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@Valid @RequestBody ModelSourceReq modelSource)
    {    boolean result=  modelSourceService.checkSourceName(modelSource);
        if (!result){
            throw new RuntimeException("英文表名称重复");
        }
        return toAjax(modelSourceService.insertModelSource(modelSource));
    }

    /**
     * 修改数据源配置
     */
    @RequiresPermissions("model:source:edit")
    @Log(title = "模型管理/数据源配置", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public AjaxResult edit(@Valid @RequestBody ModelSourceReq modelSource)
    {
        if(modelSource.getId() == null || modelSource.getId() < 1L){
            return error("请求参数缺失！");
        }
//        boolean result=  modelSourceService.checkSourceName(modelSource);
//        if (!result){
//            throw new RuntimeException("英文表名称重复");
//        }

        return toAjax(modelSourceService.updateModelSource(modelSource));
    }

    /**
     * 删除数据源配置
     */
    @RequiresPermissions("model:source:remove")
    @Log(title = "模型管理/数据源配置", businessType = BusinessType.DELETE)
    @GetMapping("/del/{ids}")
    public AjaxResult remove(@PathVariable("ids") Long[] ids)
    {
        return toAjax(modelSourceService.deleteModelSourceByIds(ids));
    }

    /**
     * 删除数据源请求参数
     */
    @RequiresPermissions("model:source:remove")
    @Log(title = "模型管理/数据源请求参数删除", businessType = BusinessType.DELETE)
    @PostMapping("/param/{id}")
    public AjaxResult remove(@PathVariable Long id)
    {
        return toAjax(modelSourceParamService.deleteModelSourceParamById(id));
    }


    /**
     * 测试数据源连接
     */
    @Log(title = "模型管理/数据源测试连接", businessType = BusinessType.OTHER)
    @PostMapping("/test8")
    public AjaxResult test8(@Valid @RequestBody ModelSourceReq modelSource) {
        Map<String,Object> paramsMap = new HashMap<>();
        if(StringUtils.isNotEmpty(modelSource.getAccount())){
            paramsMap.put("AppKey",modelSource.getAccount());
        }
        if(StringUtils.isNotEmpty(modelSource.getRequestCode())){
            paramsMap.put("AppCode",modelSource.getRequestCode());
        }
        if(StringUtils.isNotEmpty(modelSource.getSecurityKey())){
            paramsMap.put("AppSecret",modelSource.getSecurityKey());
        }
        //请求参数
        if(!CollectionUtils.isEmpty(modelSource.getSourceParams())){
            for (ModelSourceParamReq param: modelSource.getSourceParams()) {
                if(StringUtils.isNotEmpty(param.getParamName()) && StringUtils.isNotEmpty(param.getParamVal())) {
                    paramsMap.put(param.getParamName(), param.getParamVal());
                }
            }
        }
        try {
            String result = HttpRequestUtils.request(modelSource.getRequestMethod(), modelSource.getRequestUrl() ,paramsMap);
            return success(result);
        }catch (Exception e){
            logger.error("测试远程请求出错：",e);
            return error("远程测试连接失败！"+e.getMessage());
        }
    }


    @Log(title = "模型管理/数据源测试连接", businessType = BusinessType.OTHER)
    @PostMapping("/test")
    public AjaxResult test(@Valid @RequestBody ModelSourceReq modelSource) throws UnsupportedEncodingException {
        Map<String,Object> paramsMap = new HashMap<>();
        StringBuilder params = new StringBuilder();
        //请求参数
        if(!CollectionUtils.isEmpty(modelSource.getSourceParams())){
            for (ModelSourceParamReq param: modelSource.getSourceParams()) {
                if(StringUtils.isNotEmpty(param.getParamName()) && StringUtils.isNotEmpty(param.getParamVal())) {
                    paramsMap.put(param.getParamName(), param.getParamVal());
                    params.append(param.getParamName())
                            .append("=")
                            .append(param.getParamVal())
                            .append("&");
                }
            }
        }
        String strParam = "";

        if (StringUtils.isNotEmpty(params.toString())){
            strParam = params.substring(0, params.toString().length() - 1);
        }
        try {
            AjaxResult ajax = AjaxResult.success();
            String result = modelSourceService.testConnection( modelSource.getHost(), modelSource.getAccount(),
                                                                modelSource.getSecurityKey(),
                                                                modelSource.getRequestMethod(),
                                                                modelSource.getRequestUrl() ,
                                                                strParam);
            if(StringUtils.isNotEmpty(result)) {
                Optional<RemoteDataInfoDto> dataOpt = null;
                try {
                    JSONObject jsonObject = JSON.parseObject(result);
                    dataOpt = Optional.ofNullable(JSONObject.parseObject(jsonObject.getString("data"), RemoteDataInfoDto.class));
                }catch (JSONException e){
                    return error("获取远程模型数据json格式异常");
                }
                if (dataOpt.isPresent()) {
                    RemoteDataInfoDto dataInfoDto = dataOpt.get();
                    ajax.put("tableDataInfo", dataInfoDto);
                    List<?> dataList = dataInfoDto.getRows();
                    //设置表头,获取api返回数据中的一条数据，设置中文字段表头
                    if(StringUtils.isNotEmpty(dataList)) {
                        Map<String, Object> dataMap = (Map<String, Object>) dataList.get(0);
                        Map<String, Object> columnMap = new HashMap<>(dataMap.size());
//                        for(String fieldName:dataMap.keySet()){
//                            columnMap.put(fieldName,Optional.ofNullable(metaMap.get(fieldName)).orElse(""));
//                        }
                        ajax.put("columnList", columnMap);
                    }
                }else {
                    return error("获取远程模型数据json格式异常");
                }
            }else{
                ajax.put("tableDataInfo", new RemoteDataInfoDto());
            }

            return success(result);
        }catch (Exception e){
            logger.error("测试远程请求出错：",e);
            throw new RuntimeException("远程测试连接失败");
//            return error("远程测试连接失败！"+e.getMessage());
        }
    }


}
